package com.dyy.AI_System.controller;

import com.dyy.AI_System.domain.po.DocumentCategories;
import com.dyy.AI_System.domain.vo.ApiResponse;
import com.dyy.AI_System.service.IDocumentCategoriesService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 文档分类表 前端控制器
 * </p>
 *
 * @author dyy
 * @since 2025-10-14
 */
@Tag(name = "文档分类管理", description = "文档分类相关的CRUD操作API")
@RestController
@RequestMapping("/document-categories")
public class DocumentCategoriesController {

    @Autowired
    private IDocumentCategoriesService documentCategoriesService;

    /**
     * 获取所有文档分类
     */
    @Operation(summary = "获取所有文档分类", description = "查询系统中所有的文档分类信息")
    @GetMapping
    public ResponseEntity<ApiResponse<List<DocumentCategories>>> getAllCategories() {
        List<DocumentCategories> categories = documentCategoriesService.list();
        return ResponseEntity.ok(ApiResponse.success(categories));
    }

    /**
     * 根据ID获取文档分类
     */
    @Operation(summary = "根据ID获取文档分类", description = "根据分类ID查询特定文档分类的详细信息")
    @GetMapping("/{id}")
    public ResponseEntity<ApiResponse<DocumentCategories>> getCategoryById(@PathVariable("id") Long id) {
        DocumentCategories category = documentCategoriesService.getById(id);
        if (category == null) {
            return ResponseEntity.ok(ApiResponse.fail(404, "未找到该ID对应的文档分类"));
        }
        return ResponseEntity.ok(ApiResponse.success(category));
    }

    /**
     * 分页查询文档分类
     */
    @Operation(summary = "分页查询文档分类", description = "分页查询文档分类列表，支持关键词搜索")
    @GetMapping("/page")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getCategoriesByPage(
            @RequestParam(defaultValue = "1", name = "page") Integer pageNum,
            @RequestParam(defaultValue = "10", name = "size") Integer pageSize,
            @RequestParam(required = false, name = "keyword") String keyword) {

        IPage<DocumentCategories> page = documentCategoriesService.pageQuery(pageNum, pageSize, keyword);

        // 构建返回结果对象
        Map<String, Object> result = new HashMap<>();
        result.put("list", page.getRecords());
        result.put("total", page.getTotal());
        result.put("page", pageNum);
        result.put("size", pageSize);

        return ResponseEntity.ok(ApiResponse.success(result));
    }

    /**
     * 创建文档分类
     */
    @Operation(summary = "创建文档分类", description = "在系统中创建新的文档分类")
    @PostMapping
    public ResponseEntity<ApiResponse<DocumentCategories>> createCategory(@RequestBody DocumentCategories category) {
        // 设置创建时间和更新时间
        category.setCreatedAt(LocalDateTime.now());
        category.setUpdatedAt(LocalDateTime.now());
        
        boolean saved = documentCategoriesService.save(category);
        if (saved) {
            return ResponseEntity.status(HttpStatus.CREATED).body(ApiResponse.success(category));
        } else {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ApiResponse.fail(500, "创建文档分类失败"));
        }
    }

    /**
     * 更新文档分类信息
     */
    @Operation(summary = "更新文档分类信息", description = "更新指定ID文档分类的详细信息")
    @PutMapping("/{id}")
    public ResponseEntity<ApiResponse<Object>> updateCategory(
            @PathVariable("id") Long id, 
            @RequestBody DocumentCategories category) {
        // 检查分类是否存在
        DocumentCategories existingCategory = documentCategoriesService.getById(id);
        if (existingCategory == null) {
            return ResponseEntity.ok(ApiResponse.fail(404, "未找到该ID对应的文档分类"));
        }

        // 设置ID以确保更新正确的分类
        category.setId(id);
        category.setUpdatedAt(LocalDateTime.now());

        boolean updated = documentCategoriesService.updateById(category);
        if (updated) {
            return ResponseEntity.ok(ApiResponse.success("更新成功", null));
        } else {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ApiResponse.fail(500, "更新失败"));
        }
    }

    /**
     * 更新文档分类状态
     */
    @Operation(summary = "更新文档分类状态", description = "激活或禁用指定ID的文档分类")
    @PutMapping("/{id}/status")
    public ResponseEntity<ApiResponse<Object>> updateCategoryStatus(
            @PathVariable("id") Long id, 
            @RequestParam("isActive") Boolean isActive) {
        boolean updated = documentCategoriesService.updateStatus(id, isActive);

        if (updated) {
            return ResponseEntity.ok(ApiResponse.success("状态更新成功", null));
        } else {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ApiResponse.fail(500, "状态更新失败"));
        }
    }

    /**
     * 删除文档分类
     */
    @Operation(summary = "删除文档分类", description = "从系统中删除指定ID的文档分类")
    @DeleteMapping("/{id}")
    public ResponseEntity<ApiResponse<Object>> deleteCategory(@PathVariable("id") Long id) {
        boolean deleted = documentCategoriesService.removeById(id);
        if (deleted) {
            return ResponseEntity.ok(ApiResponse.success("删除成功", null));
        } else {
            return ResponseEntity.ok(ApiResponse.fail(404, "未找到该ID对应的文档分类，删除失败"));
        }
    }

    /**
     * 批量删除文档分类
     */
    @Operation(summary = "批量删除文档分类", description = "从系统中批量删除文档分类")
    @DeleteMapping("/batch")
    public ResponseEntity<ApiResponse<Object>> batchDeleteCategories(@RequestBody List<Long> ids) {
        boolean deleted = documentCategoriesService.batchDelete(ids);
        if (deleted) {
            return ResponseEntity.ok(ApiResponse.success("批量删除成功", null));
        } else {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ApiResponse.fail(500, "批量删除失败"));
        }
    }

    /**
     * 获取文档分类树结构
     */
    @Operation(summary = "获取文档分类树结构", description = "获取系统中所有文档分类的树状结构")
    @GetMapping("/tree")
    public ResponseEntity<ApiResponse<List<DocumentCategories>>> getCategoryTree() {
        List<DocumentCategories> categoryTree = documentCategoriesService.getCategoryTree();
        return ResponseEntity.ok(ApiResponse.success(categoryTree));
    }

}
